// ControllUIThread.cpp : implementation file
//

#include "stdafx.h"
#include "FastTab.h"
#include "ControllUIThread.h"
#include "UserMessage.h"
#include "TrayWnd.h"
// ControllUIThread
IMPLEMENT_DYNCREATE(ControllUIThread, CWinThread)

ControllUIThread::ControllUIThread()
{

}

ControllUIThread::~ControllUIThread()
{
}

BOOL ControllUIThread::InitInstance()
{
	TrayWnd* trayWnd = new TrayWnd();
	if(!trayWnd->Create(TrayWnd::IDD))
	{
		return FALSE;
	}

	m_pMainWnd = trayWnd;
	

	// TODO:  perform and per-thread initialization here
	return TRUE;
}

int ControllUIThread::ExitInstance()
{
	if(m_pMainWnd)
	{
		CWnd* wnd = m_pMainWnd;
		wnd->DestroyWindow();
		delete wnd;
		ASSERT(m_pMainWnd == 0);
	}
	// TODO:  perform any per-thread cleanup here
	return CWinThread::ExitInstance();
}

BEGIN_MESSAGE_MAP(ControllUIThread, CWinThread)
	ON_THREAD_MESSAGE(UserMsg::SwitchWnd, OnSwitchWnd)
	ON_THREAD_MESSAGE(UserMsg::HotkeyCallWnd, OnHotkeyCallWnd)
END_MESSAGE_MAP()

void ControllUIThread::OnSwitchWnd( WPARAM wParam, LPARAM lParam )
{
	HWND wnd = FindShowlWnd(HWND(wParam));
	SwitchToThisWindow(wnd, BOOL(lParam));
}


void ControllUIThread::OnHotkeyCallWnd( WPARAM wParam, LPARAM lParam )
{
	HWND wnd = FindShowlWnd(HWND(wParam));
	if (FindShowlWnd(::GetForegroundWindow()) == wnd)
	{
		ShowWindow(wnd, SW_MINIMIZE);
	}
	else
	{
		SwitchToThisWindow(wnd, BOOL(lParam));

	}
}
HWND ControllUIThread::FindShowlWnd( HWND hwnd )
{
	if (IsWindowEnabled(hwnd))
	{
		return hwnd;
	}
	HWND last = GetWindow(hwnd, GW_HWNDPREV);
	if (!last)
	{
		return hwnd;
	}
	if(GetWindow(last, GW_OWNER) == hwnd)
	{
		return FindShowlWnd(last);
	}
	return hwnd;

}

// ControllUIThread message handlers
